using MWTools.Client.Common;
using MWTools.Client.UI;
using System.Windows.Forms;

namespace MWToolsWordHelper
{
	using System;
	using Extensibility;
	using System.Runtime.InteropServices;
    using Office = Microsoft.Office.Core;
    using System.Reflection;
	#region Read me for Add-in installation and setup information.
	// When run, the Add-in wizard prepared the registry for the Add-in.
	// At a later time, if the Add-in becomes unavailable for reasons such as:
	//   1) You moved this project to a computer other than which is was originally created on.
	//   2) You chose 'Yes' when presented with a message asking if you wish to remove the Add-in.
	//   3) Registry corruption.
	// you will need to re-register the Add-in by building the MWToolsWordHelperSetup project, 
	// right click the project in the Solution Explorer, then choose install.
	#endregion
	
	/// <summary>
	///   The object for implementing an Add-in.
	/// </summary>
	/// <seealso class='IDTExtensibility2' />
	[GuidAttribute("2DF63B2E-7B34-4C76-890E-E8987B414F38"), ProgId("MWToolsWordHelper.Connect")]
	public class Connect : Object, Extensibility.IDTExtensibility2
	{

        private Office.CommandBarButton _commandButton;

		/// <summary>
		///		Implements the constructor for the Add-in object.
		///		Place your initialization code within this method.
		/// </summary>
        public Connect()
        {
            Logger.DebugFormat("Connect.Connect", "");
        }

		/// <summary>
		///      Implements the OnConnection method of the IDTExtensibility2 interface.
		///      Receives notification that the Add-in is being loaded.
		/// </summary>
		/// <param term='application'>
		///      Root object of the host application.
		/// </param>
		/// <param term='connectMode'>
		///      Describes how the Add-in is being loaded.
		/// </param>
		/// <param term='addInInst'>
		///      Object representing this Add-in.
		/// </param>
		/// <seealso class='IDTExtensibility2' />
		public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
		{
            _application = (Microsoft.Office.Interop.Word.Application)application;
			addInInstance = addInInst;
		}

		/// <summary>
		///     Implements the OnDisconnection method of the IDTExtensibility2 interface.
		///     Receives notification that the Add-in is being unloaded.
		/// </summary>
		/// <param term='disconnectMode'>
		///      Describes how the Add-in is being unloaded.
		/// </param>
		/// <param term='custom'>
		///      Array of parameters that are host application specific.
		/// </param>
		/// <seealso class='IDTExtensibility2' />
		public void OnDisconnection(Extensibility.ext_DisconnectMode disconnectMode, ref System.Array custom)
		{
		}

        private void createButtonControl()
        {
            Office.CommandBars oCommandBars;
            Office.CommandBar oStandardBar;

            try
            {
                oCommandBars = (Office.CommandBars)_application.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, _application, null);
            }
            catch (Exception)
            {
                // Outlook has the CommandBars collection on the Explorer object.
                object oActiveExplorer;
                oActiveExplorer = _application.GetType().InvokeMember("ActiveExplorer",
                                      BindingFlags.GetProperty,
                                      null,
                                      _application,
                                      null);
                oCommandBars = (Office.CommandBars)oActiveExplorer.GetType().InvokeMember("CommandBars",
                                                       BindingFlags.GetProperty,
                                                       null,
                                                       oActiveExplorer,
                                                       null);
            }

            // Set up a custom button on the "Standard" commandbar.
            try
            {
                oStandardBar = oCommandBars["Standard"];
            }
            catch (Exception)
            {
                // Access names its main toolbar Database.
                oStandardBar = oCommandBars["Database"];
            }

            // In case the button was not deleted, use the exiting one.
            try
            {
                _commandButton = (Office.CommandBarButton)oStandardBar.Controls["MWTools"];
            }
            catch (Exception)
            {
                object omissing = System.Reflection.Missing.Value;
                _commandButton = (Office.CommandBarButton)oStandardBar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlButton,
                                                              omissing,
                                                              omissing,
                                                              omissing,
                                                              true);
                _commandButton.Caption = "MWTools";
                _commandButton.Style = Office.MsoButtonStyle.msoButtonCaption;
            }

            // The following items are optional, but recommended. 
            //The Tag property lets you quickly find the control 
            //and helps MSO keep track of it when more than
            //one application window is visible. The property is required
            //by some Office applications and should be provided.
            _commandButton.Tag = "MWTools - Export Document";
            _commandButton.FaceId = 3804;
            _commandButton.Style = Office.MsoButtonStyle.msoButtonIconAndCaption;
            // The OnAction property is optional but recommended. 
            //It should be set to the ProgID of the add-in, so that if
            //the add-in is not loaded when a user presses the button,
            //MSO loads the add-in automatically and then raises
            //the Click event for the add-in to handle. 
            _commandButton.OnAction = "C2F1FF84-3872-4055-BB4A-7E9222863CEB";

            _commandButton.Visible = true;
            _commandButton.Click += new Office._CommandBarButtonEvents_ClickEventHandler(_commandButton_Click);
            object oName = _application.GetType().InvokeMember("Name",
                               BindingFlags.GetProperty,
                               null,
                               _application,
                               null);


            oStandardBar = null;
            oCommandBars = null;
        }

        void _commandButton_Click(Office.CommandBarButton Ctrl, ref bool CancelDefault)
        {
            Logger.DebugFormat("Connect._commandButton_Click", "");
            FrmOptions frmOptions = new FrmOptions();
            DialogResult showDialog = frmOptions.ShowDialog();

            if (showDialog == DialogResult.OK)
            {
                MessageBox.Show("Settings Saved!");
            }


           
            using (MWTools.Client.WordController controller = new MWTools.Client.WordController())
            {
                controller.SubmitContent(_application.ActiveDocument);

            }
        }


		/// <summary>
		///      Implements the OnAddInsUpdate method of the IDTExtensibility2 interface.
		///      Receives notification that the collection of Add-ins has changed.
		/// </summary>
		/// <param term='custom'>
		///      Array of parameters that are host application specific.
		/// </param>
		/// <seealso class='IDTExtensibility2' />
		public void OnAddInsUpdate(ref System.Array custom)
		{
            Logger.DebugFormat("Connect.OnAddInsUpdate", "");
		}

		/// <summary>
		///      Implements the OnStartupComplete method of the IDTExtensibility2 interface.
		///      Receives notification that the host application has completed loading.
		/// </summary>
		/// <param term='custom'>
		///      Array of parameters that are host application specific.
		/// </param>
		/// <seealso class='IDTExtensibility2' />
		public void OnStartupComplete(ref System.Array custom)
		{
            Logger.DebugFormat("Connect.OnStartupComplete", "");
            
            createButtonControl();
		}

		/// <summary>
		///      Implements the OnBeginShutdown method of the IDTExtensibility2 interface.
		///      Receives notification that the host application is being unloaded.
		/// </summary>
		/// <param term='custom'>
		///      Array of parameters that are host application specific.
		/// </param>
		/// <seealso class='IDTExtensibility2' />
		public void OnBeginShutdown(ref System.Array custom)
		{
            Logger.DebugFormat("Connect.OnBeginShutdown", "");
		}

        private Microsoft.Office.Interop.Word.Application _application;
		private object addInInstance;
	}
}